<template>
  <div class="app-container">
    <el-page-header style="margin-top: 10px; margin-bottom: 10px" @back="goBack">
      <template #content>
        <span class="header"> 项目设备管理页 </span>
      </template>
    </el-page-header>
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入关键字"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备分类" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择设备分类" filterable clearable>
            <el-option
              v-for="item in ProjectCheckInDeviceType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进/出口" prop="inOut">
          <el-select v-model="queryParams.inOut" placeholder="请选择进/出口" filterable clearable>
            <el-option label="进口" value="1"></el-option>
            <el-option label="出口" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button v-hasPerm="['sys:projectcheckindevice:add']" type="success" @click="openDialog(0, '新增')">
              <i-ep-plus />
              新增
            </el-button>
            <el-button-group v-hasPerm="['sys:projectcheckindevice:issuecommand']" style="margin-left: 12px">
              <el-button type="primary" :disabled="selectRow.length < 1" @click="toIssueCommand">
                <i-ep-finished />
                下发命令
              </el-button>
              <el-button ref="popoBtnRef" type="primary" :disabled="selectRow.length < 1" @click="toPopo">
                <el-icon v-if="!popoVisibled"><ArrowDownBold /></el-icon>
                <el-icon v-else><ArrowUpBold /></el-icon>
              </el-button>
              <el-popover
                ref="popoverRef"
                v-model="popoVisibled"
                :virtual-ref="popoBtnRef"
                trigger="click"
                virtual-triggering
                width="300"
                @show="popoShow"
                @hide="popoHide"
              >
                <el-checkbox-group
                  v-model="commandCheckList"
                  v-loading="commandPDLoading"
                  style="width: 100%"
                  @change="handleCheckboxChange"
                >
                  <el-checkbox
                    v-for="item in commandPulldownList"
                    :key="item.value"
                    border
                    :label="item.label"
                    style="width: 100%; margin-bottom: 5px"
                  ></el-checkbox>
                </el-checkbox-group>
              </el-popover>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column key="isOnline" label="在线/离线" align="center" prop="isOnline" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.isOnline ? '' : 'danger'">{{ scope.row.isOnline ? "在线" : "离线" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="name" label="设备名称" align="center" prop="name" width="180" />
        <el-table-column key="typeName" label="设备类别" align="center" prop="typeName" width="180" />
        <el-table-column key="code" label="设备序列号" align="center" width="130" prop="code"> </el-table-column>
        <el-table-column key="isDisable" label="是否禁用" align="center" width="130" prop="isDisable">
          <template #default="scope">
            <el-tag :type="scope.row.isDisable ? 'danger' : 'success'">{{
              scope.row.isDisable ? "禁用" : "启用"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="startDate" label="有效起始日期" width="160" align="center" prop="startDate" />
        <el-table-column key="endDate" label="有效截至日期" width="160" align="center" prop="endDate" />
        <el-table-column key="inOutName" label="设备进/出口" width="100" align="center" prop="inOutName" />
        <el-table-column key="model" label="设备型号" width="100" align="center" prop="model" />
        <el-table-column key="version" label="设备版本" width="100" align="center" prop="version" />
        <el-table-column key="ipAddress" label="ip地址" width="120" align="center" prop="ipAddress" />
        <el-table-column key="lastSyncTime" label="最后同步时间" width="160" align="center" prop="lastSyncTime" />
        <el-table-column key="remark" label="备注" width="200" align="center" prop="remark" />
        <el-table-column key="createTime" label="创建时间" width="160" align="center" prop="createTime" />
        <el-table-column label="操作" fixed="right" :width="mobile === 'mobile' ? 110 : 280">
          <template #default="scope">
            <el-button
              v-if="scope.row.isDisable"
              v-hasPerm="['sys:projectcheckindevice:enable']"
              type="success"
              link
              size="small"
              @click="doEnable(scope.row.id, '启用')"
            >
              <i-ep-successFilled />
              启用
            </el-button>
            <el-button
              v-else
              v-hasPerm="['sys:projectcheckindevice:disable']"
              type="danger"
              link
              size="small"
              @click="doDisable(scope.row.id, '禁用')"
            >
              <i-ep-warnTriangleFilled />
              禁用
            </el-button>
            <el-button
              v-hasPerm="['sys:projectcheckindevice:upenddate']"
              type="primary"
              link
              size="small"
              @click="handleTime(scope.row.id, scope.row.endDate)"
            >
              <i-ep-clock />
              延长限时
            </el-button>
            <el-button
              v-hasPerm="['sys:projectcheckindevice:edit']"
              type="primary"
              link
              size="small"
              @click="openDialog(scope.row.id, '编辑')"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <!--						<el-button-->
            <!--							type="primary"-->
            <!--							link-->
            <!--							size="small"-->
            <!--							@click="openDetail(scope.row.id, '详情')"-->
            <!--						>-->
            <!--							<i-ep-grid/>-->
            <!--							详情-->
            <!--						</el-button-->
            <!--						>-->
            <el-button
              v-hasPerm="['sys:projectcheckindevice:delete']"
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
            <el-button
              v-hasPerm="['sys:projectcheckindevice:delete']"
              type="success"
              link
              size="small"
              @click="openHistory(scope.row.code)"
            >
              <i-ep-watch />
              下发记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 新增/修改弹窗 -->
    <addForm
      v-if="dialogAddOrEdit.visible"
      class="system"
      :style="{ '--mobileAddFormHeight': mobile === 'mobile' ? screenHeight - 117 + 'px' : 'auto' }"
      :dialog-add-or-edit="dialogAddOrEdit"
      @sendClose="sendClose"
    ></addForm>

    <detail-description
      v-if="dialogDetail.visible"
      :dialog-detail="dialogDetail"
      class="system"
      :style="{ '--mobileAddFormHeight': mobile === 'mobile' ? screenHeight - 117 + 'px' : 'auto' }"
      @sendDetailClose="sendDetailClose"
    ></detail-description>

    <CommandHistory
      v-if="dialogHistory.visible"
      :dialog-history="dialogHistory"
      class="system"
      :style="{ '--mobileAddFormHeight': mobile === 'mobile' ? screenHeight - 100 + 'px' : 'auto' }"
      @sendHistoryClose="sendHistoryClose"
    ></CommandHistory>

    <el-dialog
      v-model="dialogTime.visible"
      title="延长限时提示"
      draggable
      width="300px"
      close-icon="CloseBold"
      @close="timeFormClose"
    >
      <el-form ref="timeFormRef" label-width="0" :model="formTime" :rules="timeRules">
        <label>延长限时</label>
        <el-form-item prop="endDate">
          <el-date-picker
            v-model="formTime.endDate"
            :disabled-date="toDisabledDate"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择延长限时"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog_footer">
          <el-button type="primary" :loading="loading" @click="doTime">确 认</el-button>
          <el-button @click="timeFormClose(true)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import addForm from "@/views/system/device/addCheckInForm.vue";
import DetailDescription from "@/views/system/device/detailCheckInDescription.vue";
import CommandHistory from "@/views/system/device/CommandHistory";
import { ParamsType, DeviceListType } from "@/api/system/device/types";
import {
  getCheckInDeviceList,
  deleteCheckInDevice,
  disableCheckInDevice,
  enableCheckInDevice,
  upenddateCheckInDevice,
  issueCommand,
} from "@/api/system/device/index.ts";
import { useUserStore } from "@/store/modules/user";
import { getDicts } from "@/store/modules/dict";
import { useRoute, useRouter } from "vue-router";

import { useScreen } from "@/store/modules/screen";
import { computed } from "vue";

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenHeight = computed(() => screenStore.screenHeight);

function initScreen() {}

const useUser = useUserStore();

/*分页列表查询*/
const total = ref(0);
const loading = ref(false);
const queryFormRef = ref(ElForm);
const addFormRef = ref();
const tableList = ref<DeviceListType[]>();

const router = useRouter();
const route = useRoute();
const projectId = ref(route.query.projectId as string);

/* 下发命令 */
const popoVisibled = ref(false);
const popoBtnRef = ref();
const popoverRef = ref();
const commandPulldownList = ref([]);
const commandCheckList = ref([]);
const commandPDLoading = ref(false);
const selectRow = ref([]);
const selectCommmand = ref([]);

const queryParams = reactive<ParamsType>({
  pageIndex: 1,
  pageSize: 20,
  projectId: projectId.value ? parseInt(projectId.value) : 0,
});

const currentUserId = useUser.objectId;

const dialogAddOrEdit = reactive<DialogOption>({
  visible: false,
  title: "新增设备信息",
  footBtn: "新增",
  projectId: projectId.value,
});

const dialogDetail = reactive<DialogOption>({
  visible: false,
  id: 0,
  title: "设备详情",
  footBtn: "",
  detail: "详情",
});

const dialogHistory = reactive<DialogOption>({
  visible: false,
  code: 0,
  title: "命令下发记录",
  footBtn: "",
  detail: "记录",
});

function goBack() {
  router.back();
}

/* 列表查询 */
async function handleQuery() {
  let list = await getCheckInDeviceList(queryParams);
  if (list.type === 0) {
    if (list.success) {
      tableList.value = list.data.list;

      queryParams.pageIndex = list.data.pageNum;
      queryParams.pageSize = list.data.pageSize;
      total.value = list.data.total;
    } else {
      ElMessage.error(list.msg);
    }
  } else {
    ElMessage.error(list.msg);
  }
}

const handleSelectionChange = (selection) => {
  selectRow.value = [];
  selection.map((item) => {
    selectRow.value.push(item.id);
  });
};

const handleCheckboxChange = (selection) => {
  let temp;
  selectCommmand.value = [];
  selection.map((item) => {
    temp = commandPulldownListFilter(item);
    if (temp) {
      selectCommmand.value.push(temp);
    }
  });
};

function commandPulldownListFilter(val) {
  let temp;
  if (val) {
    temp = commandPulldownList.value.filter((i) => i.label === val);
    if (temp && temp.length > 0) {
      return temp[0].value;
    } else {
      return "";
    }
  }
}

function toIssueCommand() {
  if (selectRow.value && selectRow.value.length < 1) {
    ElMessage.warning("请选择命令下发机器!");
    return;
  }
  if (selectCommmand.value && selectCommmand.value.length < 1) {
    ElMessage.warning("请选择下发命令!");
    return;
  }
  issueCommand(selectRow.value.toString(), selectCommmand.value.toString())
    .then((data) => {
      if (data.success) {
        ElMessage.success(data.msg);
      } else {
      }
    })
    .catch(() => {
      commandCheckList.value = [];
      selectCommmand.value = [];
    });
}

function toPopo() {
  popoVisibled.value = !popoVisibled.value;
}

function popoShow() {
  commandPDLoading.value = false;
  commandPulldownList.value = getDicts("checkInCommandType"); //银行类别
  // getCheckInDeviceCommandPulldownList().then(data => {
  // 	commandPulldownList.value = data.data.list;
  // 	commandPDLoading.value = false;
  // })
  popoVisibled.value = true;
}

function popoHide() {
  commandCheckList.value = [];
  selectCommmand.value = [];
  popoVisibled.value = false;
}

/* 新增/编辑 */
function openDialog(id, detail) {
  dialogAddOrEdit.visible = true;
  if (id) {
    dialogAddOrEdit.title = "修改考勤设备信息";
    dialogAddOrEdit.footBtn = "修改";
    dialogAddOrEdit.id = id;
  } else {
    dialogAddOrEdit.id = 0;
    dialogAddOrEdit.title = "新增考勤设备信息";
    dialogAddOrEdit.footBtn = "新增";
  }
  dialogAddOrEdit.detail = detail;
}

function openDetail(id, detail) {
  dialogDetail.title = "考勤设备详情";
  dialogDetail.footBtn = "";
  dialogDetail.id = id;
  dialogDetail.detail = detail;
  dialogDetail.visible = true;
}

function openHistory(code, detail) {
  dialogHistory.title = "命令下发记录";
  dialogHistory.code = code;
  dialogHistory.visible = true;
}

async function doDisable(id) {
  let confirm = await ElMessageBox.confirm("确认禁用?", "禁用提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => true)
    .catch(() => false);
  if (!confirm) {
    ElMessage({
      type: "info",
      message: "已取消！",
    });
    return;
  }
  disableCheckInDevice(id).then((data) => {
    if (data.success) {
      ElMessage.success(data.msg);
    } else {
    }
  });
  handleQuery();
}

async function doEnable(id) {
  let confirm = await ElMessageBox.confirm("确认启用?", "启用提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => true)
    .catch(() => false);
  if (!confirm) {
    ElMessage({
      type: "info",
      message: "已取消！",
    });
    return;
  }
  enableCheckInDevice(id).then((data) => {
    if (data.success) {
      ElMessage.success(data.msg);
    } else {
    }
  });
  handleQuery();
}

const dialogTime = reactive({
  id: 0,
  visible: false,
});

const timeRules = {
  endDate: [{ required: true, trigger: "blur", message: "请选择时间!" }],
};

const formTime = reactive({
  endDate: "",
});

const timeFormRef = ref();

function handleTime(id, endDate) {
  dialogTime.id = id;
  formTime.endDate = endDate;
  dialogTime.visible = true;
}

function toDisabledDate(val) {
  return formTime.endDate < val;
}

function doTime() {
  timeFormRef.value.validate((valid) => {
    if (valid) {
      upenddateCheckInDevice(dialogTime.id, formTime.endDate).then((data) => {
        if (data.success) {
          ElMessage.success(data.msg);
          timeFormClose();
          handleQuery();
        } else {
        }
      });
    }
  });
}

function timeFormClose(quxiao) {
  if (quxiao) {
    ElMessage({
      type: "info",
      message: "已取消!",
    });
  }
  timeFormRef.value.resetFields();
  timeFormRef.value.clearValidate();
  dialogTime.visible = false;
}

/* 删除班组 */
async function handleDelete(id) {
  let confirm = await ElMessageBox.confirm("确认删除?", "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => true)
    .catch(() => false);
  if (!confirm) {
    ElMessage({
      type: "info",
      message: "已取消！",
    });
    return;
  }
  let delInfo = await deleteCheckInDevice(id);
  if (delInfo.type === 0) {
    if (delInfo.success) {
      ElMessage.success(delInfo.msg);
      resetQuery();
    } else {
      ElMessage.error(delInfo.msg);
    }
  } else {
    ElMessage.error(delInfo.msg);
  }
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageIndex = 1;
  queryParams.pageSize = 20;
  queryParams.projectId = projectId.value;
  handleQuery();
}

/* 关闭弹窗并刷新列表 */
function sendClose(query) {
  dialogAddOrEdit.visible = false;
  if (query) {
    handleQuery();
  }
}

function sendDetailClose(query) {
  dialogDetail.visible = false;
}

function sendHistoryClose(query) {
  dialogHistory.visible = false;
}

onMounted(() => {
  initScreen();

  handleQuery();
});

function bankTypeFilter(type) {
  let tempType = BankTypeTypes.filter((item) => item.value == type);
  if (tempType[0] && tempType[0].label) {
    return tempType[0].label;
  } else {
    return;
  }
}

const BankTypeTypes = getDicts("bankTypeTypes"); //银行类别
const ProjectCheckInDeviceType = getDicts("projectCheckInDeviceType"); //银行类别
</script>

<style lang="less" scoped>
:deep(.el-divider--vertical) {
  border-left-color: black;
}

.header {
  font-size: 18px;
  font-weight: 700;
}
</style>
